/*******************************************************************************
 * Copyright (c) 2008 CEA LIST.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA LIST - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.classdiagram.parsers.texteditor.portlabel;

import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.uml2.uml.Port;

import com.cea.papyrus.classdiagram.parsers.modelgenerator.PortGenerator;
import com.cea.papyrus.extensionpoints.editors.configuration.DefaultDirectEditorConfiguration;

/**
 * 
 */
public class PortConfigurationForUML extends DefaultDirectEditorConfiguration  {

	/** configuration of the source viewer */
	final private PortLabelSourceViewerConfiguration configuration;

	/**
	 * Creates a new PortConfigurationForUML.
	 */
	public PortConfigurationForUML() {
		configuration = new PortLabelSourceViewerConfiguration();
	}
	
	/**
	 * {@inheritDoc}
	 */
	public SourceViewerConfiguration getSourceViewerConfiguration() {
		return configuration;
	}

	/**
	 * {@inheritDoc}
	 */
	public String getTextToEdit(Object editedObject) {
		if(editedObject instanceof Port) {
			return getLabel((Port)editedObject);
		}
		return "not a Port";
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object preEditAction(Object objectToEdit) {
		if(objectToEdit instanceof Port) {
			configuration.setPort((Port)objectToEdit);
		}
		return super.preEditAction(objectToEdit);
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Object postEditAction(Object editedObject, String text) {
		if(editedObject instanceof Port) {
			PortGenerator generator = new PortGenerator(((Port)editedObject));
			generator.parseAndModifyPort(text);
		}
		return null;
	}
	
	/**
	 * Gets the label.
	 * @return the label
	 */
	public String getLabel(Port port) {
		String type="<undefined>";
		if (port.getType()!=null){
			type=port.getType().getName();
		}

		return port.getName()+": "+type;
	}

	@Override
	public IInputValidator getInputValidator() {
		return new IInputValidator() {
		
			public String isValid(String newText) {
				if(getObjectToEdit() instanceof Port) {
					PortGenerator generator = new PortGenerator(((Port)getObjectToEdit()));
					return generator.parseAndValidatePort(newText);
				}
				return null;
			}
		};
	}
	
}
